package com.yeskery.nut.extend.mybatis;

import com.yeskery.nut.transaction.TransactionManager;
import org.apache.ibatis.session.TransactionIsolationLevel;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Properties;

/**
 * Nut事务工厂
 * @author Yeskery
 * 2023/7/25
 */
public class NutTransactionFactory extends ManagedTransactionFactory {

    /** 是否设置关闭时自动提交 */
    private boolean skipSetAutoCommitOnClose;

    /** 事务管理器 */
    private final TransactionManager transactionManager;

    /**
     * 构建Nut事务工厂
     * @param transactionManager 事务管理器
     */
    public NutTransactionFactory(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Override
    public void setProperties(Properties props) {
        if (props != null) {
            String value = props.getProperty("skipSetAutoCommitOnClose");
            if (value != null) {
                this.skipSetAutoCommitOnClose = Boolean.parseBoolean(value);
            }
        }
    }

    @Override
    public Transaction newTransaction(Connection connection) {
        return new NutTransaction(transactionManager, connection, skipSetAutoCommitOnClose);
    }

    @Override
    public Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean b) {
        return new NutTransaction(transactionManager, dataSource, level, skipSetAutoCommitOnClose);
    }
}
